<template>
  <div>
    <el-form
      class="windows_box"
      ref="formName"
      style="width: 100%"
      label-position="top"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" size="small"> </el-input>
      </el-form-item>

      <!-- <div v-if="form.type"> -->

      <!-- 拖拽框 -->
      <el-form-item label="属性">
        <div
          class="attributeDrag"
          id="Drag"
          v-if="form.attributeList.length !== 0"
        >
          <draggable
            v-model="form.attributeList"
            group="people"
            @start="drag = true"
            @end="drag = false"
          >
            <div
              class="node_attr_item"
              v-for="(v, i) in form.attributeList.slice(
                (pageNo - 1) * pageSize,
                pageNo * pageSize
              )"
              :key="i"
            >
              <el-input
                size="mini"
                v-model="v.name"
                class="input-with-select prepend_box"
              >
                <el-select
                  v-model="v.type"
                  slot="prepend"
                  placeholder="请选择"
                  style="
                    appearance: none;
                    -moz-appearance: none;
                    -webkit-appearance: none;
                  "
                >
                  <el-option
                    v-for="type in seleType"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  ></el-option>
                </el-select>
              </el-input>
              <!-- 删除按钮 -->
              <el-tooltip
                class="item"
                effect="dark"
                content="拖拽调整顺序"
                placement="right"
              >
                <svg-icon
                  class="draganddrop"
                  icon-class="draganddrop"
                ></svg-icon>
              </el-tooltip>
              <svg-icon
                class="trash"
                icon-class="trash"
                @click="delAttribute(i)"
              ></svg-icon>
            </div>
          </draggable>
        </div>

        <el-pagination
          v-show="form.attributeList.length !== 0"
          size="mini"
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page.sync="pageNo"
          :page-sizes="[5, 10]"
          :page-size="pageSize"
          :total="form.attributeList.length"
          layout="sizes, prev, pager, next"
        >
        </el-pagination>
      </el-form-item>
      <el-form-item label="">
        <el-input
          size="mini"
          v-model="form.seleName"
          class="input-with-select prepend_box"
          clearable
        >
          <el-select
            v-model="form.seleType"
            slot="prepend"
            placeholder="请选择"
            value-key
          >
            <el-option
              v-for="type in seleType"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            ></el-option>
          </el-select>
          <el-button
            slot="append"
            icon="el-icon-plus"
            style="width: 110px"
            @click="addAttribute"
            >添加属性</el-button
          >
        </el-input>
      </el-form-item>
      <el-form-item label="窗口类型" prop="type">
        <PopoverInput
          v-model="form.type"
          keys="windowsBox"
          objKey="windowArr"
          @changeRadio="changeRadio"
          @input="inputVal"
        ></PopoverInput>
      </el-form-item>
      <FlowHandleItem
        @handItemDel="handItemDel"
        @handItemAdd="handItemAdd"
        v-show="true"
        :isAdd="true"
        :parameters="form.parameters"
        objKey="value"
      ></FlowHandleItem>
    </el-form>
    <!-- 确认取消公共组件 -->
    <TopOperationButton
      @submit="submit"
      @handClose="handClose"
      style="margin-right: 30px; margin-top: 10px"
    />
  </div>
</template>

<script>
let that = null;
import FlowHandleItem from "./component/FlowHandleItem";
import PopoverInput from "@/components/PopoverInput";
import { valiType } from "../inputSourcePage/js/index";
import { mapGetters } from "vuex";
import { delay, generateId } from "@/utils/index";
import draggable from "vuedraggable";
import TopOperationButton from "../CommonComponents/TopOperationButton";
import {
  setFlow,
  mapParameterValues,
  obtainStreamFunctionsFromResponse,
} from "./js/index";
import _ from "lodash";
export default {
  components: {
    PopoverInput,
    draggable,
    TopOperationButton,
    FlowHandleItem,
  },
  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    ...mapGetters(["extensions", "metadata"]),
    validatorForm() {
      return function (rule, value, callback, item) {
        // 如果没选中,直接返回
        if (item.isCheck === false) {
          callback();
        }
        const msg = valiType(value, item.type);
        if (msg.length === 0) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
    // 自定义校验自定义属性的参数
    validator() {
      return function (rule, value, callback) {
        var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(
            new Error("属性名称首位必须为字母且不能包含特殊符号和空格!!")
          );
        }
      };
    },
  },
  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        let tempdata = _.cloneDeep(newData);
        this.$store.commit("projection/setExtensions", {
          relateData: tempdata ? tempdata.relateData : {},
        });

        console.log("节点信息", tempdata);
        this.dataId = tempdata.id;
        const { name, objectState, parameters, type, attributeList } = tempdata;

        // 保存最后提交使用
        this.subType = type;
        // 原始数据
        this.parameters = parameters;
        // parameters =
        if (name) {
          const values = mapParameterValues(
            {
              function: type,
              parameters: parameters,
            },
            obtainStreamFunctionsFromResponse(this.metadata)[
              "windowFunctionNames"
            ]
          );
          // this.form = tempdata;
          const arr = values.parameters || [];
          this.form.type = values.functionName || "";
          this.form.parameters = arr || [];
          this.form.attributeList = attributeList || [];
          this.form.name = name || "";
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      dataId: "",
      parameters: [],
      subType: "",
      seleType: [
        { id: "STRING", name: "string" },
        { id: "INT", name: "int" },
        { id: "LONG", name: "long" },
        { id: "FLOAT", name: "float" },
        { id: "DOUBLE", name: "double" },
        { id: "BOOL", name: "bool" },
        { id: "OBJECT", name: "object" },
      ],
      pageNo: 1,
      pageSize: 5,
      totalNum: 0,
      rules: {
        name: [
          {
            required: true,
            message: "名称不能为空",
          },
        ],
        type: [
          {
            required: true,
            message: "窗口类型不能为空",
          },
          {
            validator(rule, value, callback) {
              delay(() => {
                let isExistence = "";
                for (let i = 0; i < that.extensions.windowArr.length; i++) {
                  const item = that.extensions.windowArr[i];
                  isExistence = item.list.find((e) => e.valueType == value);
                  // 如果存在,跳出循环
                  if (isExistence) {
                    break;
                  }
                }
                // that.extensions.windowArr.forEach((item) => {});

                if (isExistence) {
                  // 如果存在就直接循环出来列表
                  callback();
                } else {
                  that.form.parameters = [];
                  callback(new Error("与任何项目都不匹配"));
                }
              }, 500);
            },
          },
        ],
      },
      form: {
        name: "",
        seleType: "STRING",
        seleName: "",
        parameters: [],
        type: "",
        attributeList: [],
        outputEventType: "",
      },
    };
  },
  created() {
    that = this;
  },
  methods: {
    submit() {
      this.$refs["formName"].validate((valid) => {
        if (valid) {
          if (
            this.$store.getters["siddhi/streamKeyIsRepear"]({
              id: this.dataId,
              val: this.form.name,
            })
          ) {
            this.$msg("流节点,表格节点,窗口节点名称不能重复!");
            return false;
          }

          // this.$set(this.form, "parameters2", setFlow(this.form.parameters));

          // this.form.type = this.subType;

          const isattr =
            this.form.attributeList.length != 0 &&
            this.form.attributeList.some((item) => item.name != "");
          if (!isattr) {
            this.$msg("请完善节点属性");
            return;
          }
          const form = _.cloneDeep(this.form);
          form.type = this.subType;
          form.parameters = setFlow(this.form.parameters);
          let returnData = {
            display: false,
            objectState: this.nodeDataRight.objectState,
            nodeData: form,
            type: "windowList",
            nodeDataRight: this.nodeDataRight,
          };
          this.$emit("returnSource", returnData);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handClose() {
      this.$emit("handClose");
    },
    // 删除
    handItemDel(index, eIndex) {
      this.form.parameters[index].value.splice(eIndex, 1);
    },
    // 带...的 动态添加属性
    handItemAdd(item, index) {
      // 这里不做深拷贝,页面不更新
      let arr = _.cloneDeep(this.form.parameters);
      const obj = {
        defaultValue: "",
        description: "",
        isDynamic: true,
        name: "",
        optional: true,
        isDel: true,
        id: generateId(),
        value: "",
      };
      arr[index].value.push(obj);
      this.$set(this.form, "parameters", arr);
      this.$forceUpdate();
    },
    // 属性列表添加
    addAttribute() {
      // if(!this.check()){
      //   return
      // }
      var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
      if (!this.form.seleName) {
        this.$msg("请输入属性名称");
        return;
      }
      if (!this.form.seleType) {
        this.$msg("请选择属性类型");
        return;
      }
      if (!reg.test(this.form.seleName)) {
        this.$msg("属性名称首位必须为字母且不能包含特殊符号和空格");
        return;
      }
      const isRepeat = this.form.attributeList.some(
        (item) => item.seleName == this.form.seleName
      );
      if (isRepeat) {
        this.$msg("属性名称不能重复");
        return;
      }
      this.form.attributeList.push({
        //   this.form
        type: this.form.seleType,
        name: this.form.seleName,
      });
      this.form.seleName = "";
      //   this.form.seleType = "";
      //添加属性之后 回到第一页
      this.pageNo = 1;
    },

    sizeChange(val) {
      this.pageSize = val;
      this.pageNo = 1;
    },
    currentChange(val) {
      this.pageNo = val;
    },
    // 属性列表删除
    delAttribute(i) {
      this.form.attributeList = this.form.attributeList.filter(
        (v, index) => index != i
      );
    },
    inputVal(val) {
      console.log("row", val);
    },
    changeRadio(row) {
      const values = this.getFunNamePar(row.name, []);
      const { functionName, parameters } = values;
      this.form.type = functionName;
      this.subType = row.name;
      this.form.parameters = parameters;
    },
    getFunNamePar(name, parameters) {
      const values = mapParameterValues(
        {
          function: name,
          parameters,
        },
        obtainStreamFunctionsFromResponse(this.metadata)["windowFunctionNames"]
      );
      return values;
    },
  },
};
</script>

<style lang='scss' scoped>
.windows_box {
  padding: 0 30px;
  border-top: 1px solid #e4e4e4;
  border-bottom: 1px solid #e4e4e4;
  height: calc(100vh - 140px);
  overflow-y: auto;
  .attributeDrag {
    margin-top: 0;
  }
  .node_attr_item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  /deep/ .el-form-item__label {
    width: 100px;
    padding-bottom: 0;
  }
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}
</style>